<template>
  <div class="main">
    <section>
      <search-form
        :listQuery="queryParams"
        :queryConfig="queryConfig"
        :labelWidth="100"
        :search="search"
      />
      <div style="margin-bottom:20px">
        <el-popover placement="right" title="同步订单" trigger="click"   v-model="syncVisible">
          <el-date-picker
            v-model="syncTime.date"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
          <el-time-picker
            v-model="syncTime.startTime"
            start-placeholder="开始时间"
            value-format="HH:mm:ss"
            placeholder="选择时间范围">
          </el-time-picker>
          <el-time-picker
            v-model="syncTime.endTime"
            value-format="HH:mm:ss"
            start-placeholder="结束时间"
            :picker-options="{
              selectableRange: syncTime.selectableRange
            }"
            placeholder="选择时间范围">
          </el-time-picker>
          <el-button type="primary" plain @click="_syncOrder" style="margin-top:20px" >同 步</el-button>
          <el-button v-if="rightsButtons['sync']" type="primary" slot="reference" @click="syncVisible = true ">马上同步</el-button>
        </el-popover>
      </div>

      <el-table
        v-loading="loading"
        :data="list"
        element-loading-text="给我一点时间"
        border
        fit
        header-row-class-name="table-header"
        highlight-current-row
      >
        <el-table-column align="center" label="订单平台">
          <template slot-scope="scope">
            <span>{{scope.row.platform==='ALI'?'淘宝':scope.row.platform==='PDD'?'拼多多':scope.row.platform==='JD'?'京东':'唯品会'}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="订单编号">
          <template slot-scope="scope">
            <span>{{scope.row.parentTid}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商品图片" width="130">
          <template slot-scope="scope">
            <img :src="scope.row.imageUrl" style="height: 50px;" alt />
          </template>
        </el-table-column>
        <el-table-column align="center" label="标题" width="210">
          <template slot-scope="scope">
            <span>{{scope.row.title}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="付款金额(元)" prop="merchantName" min-width="160">
          <template slot-scope="scope">
            <span>{{scope.row.payment}}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="购买数量" width="90">
          <template slot-scope="scope">
            <span>{{scope.row.num||0}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="购买者(碧选手机号)" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.nick}} - {{scope.row.mobile}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="购买者(渠道号)" width="110">
          <template slot-scope="scope">{{scope.row.relationId}}</template>
        </el-table-column>
        <el-table-column align="center" label="下单时间" min-width="160">
          <template slot-scope="scope">
            <span>{{scope.row.tradePayTime}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="预估佣金(元)" width="80">
          <template slot-scope="scope">
            <span>{{scope.row.commission}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="淘宝佣金比例(%)" width="80">
          <template slot-scope="scope">
            <span>{{scope.row.commissionRate}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="交易状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.tradeStatus === 'TRADE_INVALID'" style="color:red" >{{scope.row.tradeStatus|tradeStatus}}</span>
            <span v-else>{{scope.row.tradeStatus|tradeStatus}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="结算状态" width="100">
          <template slot-scope="scope">
            <span>{{scope.row.settleStatus |settleStatus}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              v-if="rightsButtons['predictDetail'] && scope.row.settleStatus !== 'TRADE_INVALID' "
              type="primary"
              @click="showCommission(scope.row,0)"
              plain
            >预估佣金明细</el-button>
            <el-button
              v-if="rightsButtons['realDetail'] && scope.row.settleStatus == 'TRADE_DONE_SETTLE'"
              type="primary"
              plain
              @click="showCommission(scope.row,1)"
            >实发佣金明细</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100, 200]"
        :page-size="queryParams.pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal"
      ></el-pagination>
    </section>
    <el-dialog :title="currentType===0? '预估佣金明细' :'实际佣金明细'" :visible.sync="commissionDialg">
      <p>订单号&nbsp;&nbsp;&nbsp;：{{currentOrder.tid}}</p>
      <p style="margin:20px 0px">产生佣金：{{totalCommission}}</p>
      <el-table :data="commissionList">
        <el-table-column label="佣金类型" width="150">
          <template slot-scope="scope">{{scope.row.buyerType==='SELF_BUYING'?'自购佣金':"团队佣金"}}</template>
        </el-table-column>
        <el-table-column label="获佣用户手机号" width="200">
          <template slot-scope="scope">{{scope.row.mobile || '-'}}</template>
        </el-table-column>
        <el-table-column label="获佣用户身份" width="150">
          <template
            slot-scope="scope"
          >{{( currentType === 0?scope.row.prepareRole :scope.row.realRole) | userRole}}</template>
        </el-table-column>
        <el-table-column label="获佣用户等级" width="150">
          <template
            slot-scope="scope"
          >{{(currentType === 0?scope.row.prepareLevel : scope.row.realLevel)| userLevel}}</template>
        </el-table-column>

        <el-table-column width="150" label="获得佣金比列(%)">
          <template
            slot-scope="scope"
          >{{currentType === 0? scope.row.prepareCommissionRate :scope.row.realCommissionRate}}</template>
        </el-table-column>
        <el-table-column width="150" label="佣金数值(元)">
          <template
            slot-scope="scope"
          >{{ currentType === 0? scope.row.prepareCommission:scope.row.realCommission}}</template>
        </el-table-column>
      </el-table>
      <p style="margin-top:20px">
        {{
        currentType === 0? `预估平台剩余：${currentOrder.residuePrepareCommission}`:
        `实际平台剩余：${currentOrder.residueRealCommission}`
        }}
      </p>
    </el-dialog>
  </div>
</template>
<script>
import searchForm from "@/components/searchForm/index";
import { searchOrderList, getTradeRecord, syncOrder } from "@/api/bihuasuan/order";
import moment from 'moment';

export default {
  name: "b-orderManage",
  components: {
    searchForm
  },
  filters: {
    tradeStatus(val) {
      const TRADE_STATUS = {
        TRADE_PAY: "已付款",
        TRADE_EARNING: "已结算",
        TRADE_SUCCESS: "已收货",
        TRADE_INVALID: "已失效"
      };
      return TRADE_STATUS[val];
    },
    settleStatus(val) {
      const SETTLE_STATUS = {
        TRADE_WAIT_SETTLE: "等待结算",
        TRADE_INVALID: "佣金失效",
        TRADE_DONE_SETTLE: "结算成功"
      };
      return SETTLE_STATUS[val];
    },
    userRole(val) {
      const type = {
        '0': '普通会员',
        '1': 'VIP会员',
        '2': '钻石会员',
        '3': '董事会员',
      };
      if (val === null) return "-";
      return type[val];
    },
    userLevel(val) {
      const type = {
        1: "LV1",
        2: "LV2",
        3: "LV3",
        4: "LV4",
        5: "LV5",
        6: "LV6",
        7: "LV7",
        8: "LV8",
        9: "LV9"
      };

      if (val === null) return "-";
      return type[val];
    }
  },
  data() {
    return {
      syncVisible: false,
      syncTime:{startTime:'', endTime:'', selectableRange:'', date:''},
      currentOrder: "",
      commissionList: [],
      currentType: "", // 0预估   1实际
      commissionDialg: false,
      totalCommission: 0,
      queryParams: {
        endTradeCreateTime: "",
        mobile: "",
        orderBy: "",
        pageNum: 0,
        pageSize: 50,
        parentTid: "",
        platform: "",
        settleStatus: "",
        startTradeCreateTime: "",
        title: "",
        tradeStatus: ""
      },
      queryConfig: [
        {
          prop: "platform",
          type: "select",
          label: "平台",
          data: []
        },
        {
          prop: "tradeStatus",
          type: "select",
          label: "订单状态",
          data: [
            {
              label: "全部",
              value: ""
            },
            {
              label: "已付款",
              value: "TRADE_PAY"
            },
            {
              label: "已收货",
              value: "TRADE_SUCCESS"
            },
            {
              label: "已结算",
              value: "TRADE_EARNING"
            },
            {
              label: "已失效",
              value: "TRADE_INVALID"
            }
          ]
        },
        {
          prop: "settleStatus",
          type: "select",
          label: "结算状态",
          data: [
            {
              label: "全部",
              value: ""
            },
            {
              label: "等待结算",
              value: "TRADE_WAIT_SETTLE"
            },
            {
              label: "佣金失效",
              value: "TRADE_INVALID"
            },
            {
              label: "结算成功",
              value: "TRADE_DONE_SETTLE"
            }
          ]
        },
        {
          prop: "mobile",
          type: "input",
          label: "碧选手机号"
        },
        {
          prop: "parentTid",
          type: "input",
          label: "订单号"
        },
        {
          prop: "title",
          type: "input",
          label: "商品标题"
        },
        {
          prop: "createDate",
          type: "daterange",
          label: "下单时间"
        }
      ],
      loading: true,
      listTotal: 0,
      list: []
    };
  },
  watch: {
    'syncTime.startTime'() {
      let startTime = moment(this.syncTime.startTime, "HH:mm:ss").add(1, 'm').format('HH:mm:ss');
      let endTime =  moment(this.syncTime.startTime, "HH:mm:ss").add(11, 'm').format('HH:mm:ss');
      this.syncTime.selectableRange = `${startTime} - ${endTime}`
    }
  },
  created() {
    this.initPlatform()
    this.getList()
  },
  methods: {
    initPlatform () {
      this.request({
        url: '/bihs/search-platform/list',
        method: 'get'
      }).then((data) => {
        data.data.forEach((element) => {
          this.queryConfig[0].data.push({
            value: element.platform,
            label: element.name
          });
        })
      }).catch(err => {
        console.log(err);
        this.queryConfig[0].data = []
      });
    },
    async getList() {
      this.loading = true;
      const params = { ...this.queryParams };
      delete params.createDate;
      try {
        const { data } = await searchOrderList(params);
        this.loading = false;
        this.list = data.list;
        this.listTotal = data.total;
      } catch (error) {
        console.log(error);
        this.list = [];
        this.listTotal = 0;
        this.loading = false;
      }
    },
    async showCommission(val, type) {
      this.currentType = type;
      this.currentOrder = val;
      try {
        const { data } = await getTradeRecord({ tid: val.tid });
        this.commissionList = data;
        this.commissionDialg = true;
        this.getTotalCommission();
      } catch (error) {
        console.log(error);
      }
    },
    // 同步订单
    async _syncOrder() {
      try {
        const {data} = await syncOrder(
            {
              startTime:`${this.syncTime.date} ${this.syncTime.startTime}`,
              endTime:`${this.syncTime.date} ${this.syncTime.endTime}`
            }
          )
        if (data) {
          this.syncVisible = false
          this.$message.success('同步成功')
          this.getList()
        }else {
          this.$message.error('同步失败')
        }
      } catch (error) {
        this.$message.error('操作失败')
        console.log(error)
      }
    },
    // 获取产生总佣金金额   用户产生+平台剩余
    getTotalCommission() {
      // 真实佣金
      if (this.currentType === 1) {
        this.totalCommission = this.commissionList
          .reduce((a, b) => {
            return a + Number(b.realCommission);
          }, this.currentOrder.residueRealCommission || 0)
          .toFixed(2);
      } else if (this.currentType === 0) {
        // 预估佣金总额
        this.totalCommission = this.commissionList
          .reduce((a, b) => {
            return a + Number(b.prepareCommission);
          }, this.currentOrder.residuePrepareCommission || 0)
          .toFixed(2);
        console.log("@!!@", this.totalCommission);
      }
    },
    search() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.createDate && this.queryParams.createDate[0]) {
        this.queryParams.startTradeCreateTime = this.queryParams.createDate[0];
        this.queryParams.endTradeCreateTime = this.queryParams.createDate[1];
      } else {
        this.queryParams.startTradeCreateTime = "";
        this.queryParams.endTradeCreateTime = "";
      }

      this.getList();
    },
    handleSizeChange(value) {
      this.queryParams.pageSize = value;
      this.getList();
    },
    handleCurrentChange(value) {
      this.queryParams.pageNum = value;
      this.getList();
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-dialog {
  max-width: 990px;
}
</style>
